//
//
//
//		宗申通机
//		
//
const app = getApp()
var bluetooth = require('../../command/bluetooth.js')

function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}

Page({
  data: {
    devices: [],
    connected: false,
    chs: [], 
    misScanding: false,
    scandbutName:"搜索蓝牙设备",
    m_QRdevice: "", //蓝牙设备码 mac码
    m_QRdeviceName: "", //蓝牙名称
    overlayVisible:false,
  },
  autoConnect : false,

  openBluetoothAdapter(autoConnect = false) {
    console.log("进入打开蓝牙页面")
    this.setData({ misScanding: true })
    // this.setData({ overlayVisible: true })
    this.autoConnect = autoConnect
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log('openBluetoothAdapter success', res)
        this.startBluetoothDevicesDiscovery()
      },
      fail: (res) => {
        if (res.errCode === 10001) {
          wx.onBluetoothAdapterStateChange(function (res) {
            console.log('onBluetoothAdapterStateChange', res)
            if (res.available) {
              this.startBluetoothDevicesDiscovery()
            }
          })
        }
      }
    })
  },
  getBluetoothAdapterState() {
    wx.getBluetoothAdapterState({
      success: (res) => {
        console.log('getBluetoothAdapterState', res)
        if (res.discovering) {
          this.onBluetoothDeviceFound()
        } else if (res.available) {
          this.startBluetoothDevicesDiscovery()
        }
      }
    })
  },
  scanBluetoothQRCode() {
    // 只允许从相机扫码
    wx.scanCode({
      onlyFromCamera: true,
      success: (res) => {
        console.log(res)
        let temp = res.result
        this.m_QRdevice = res.result
        // for(let i = 0; i < temp.length; i+=2){
        //   this.m_QRdevice += temp.substring(i, i+2) + ":"
        // }
        // this.m_QRdevice = this.m_QRdevice.substr(0, this.m_QRdevice.length-1)
        console.log(this.m_QRdevice)
        this.openBluetoothAdapter(true)
      }
    })
  },
  connectDefaultDevice(){
    console.log("connectDefaultDevice")
    // WSHwx.request({
    //   url: 'url',
    // })
    this.m_QRdevice = app.globalData.bluetoothName ; // app.globalData.bluetoothMac
    console.log(this.m_QRdevice)
    this.openBluetoothAdapter(true)
  },
  startBluetoothDevicesDiscovery() {
    console.log("启动Blue")
    var that = this;
    if (this._discoveryStarted) {
      this.stopBluetoothDevicesDiscovery()
      return
    }
    this.setData({ misScanding: true, 
    scandbutName: "正在搜索，点击停止", 
      devices: [],
      chs: [],
    })
    //console.log('lisn3188---------- misScanding = ', this.misScanding)
    this._discoveryStarted = true
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      success: (res) => {
        setTimeout(function () {
          console.log("----BluetoothDevicesDiscovery finish---- ");
          console.log("检测完成")
          this.overlayVisible = false
          if (that._discoveryStarted){
            that.stopBluetoothDevicesDiscovery()
          }
        }, 20000);
        console.log('startBluetoothDevicesDiscovery success', res)
        this.onBluetoothDeviceFound()
      },
    })
  },
  stopBluetoothDevicesDiscovery() {
    this._discoveryStarted = false
    this.setData({ misScanding: false, scandbutName:"重新刷新列表", })
    wx.stopBluetoothDevicesDiscovery()
    //console.log('lisn3188---------- misScanding = ', this.misScanding)
  },
  onBluetoothDeviceFound() {
    wx.onBluetoothDeviceFound((res) => {
      res.devices.forEach(device => {
        if (!device.name && !device.localName) {
          return
        }
        const foundDevices = this.data.devices
        const idx = inArray(foundDevices, 'deviceId', device.deviceId)
        const data = {}
        if (idx === -1) {
          data[`devices[${foundDevices.length}]`] = device
        } else {
          data[`devices[${idx}]`] = device
        }
        this.setData(data)
        // device.deviceId
        console.log("device :", device, this.m_QRdevice, device.name)
        if(this.autoConnect===true && this.m_QRdevice == device.name){
            console.log('蓝牙配队成功，mac地址：', this.m_QRdevice)
            app.globalData.ble_device = device
            this.stopBluetoothDevicesDiscovery()
            // wx.navigateTo({
            //   url: '/pages/device/home/home',
            // })
            this.gotoconnect()
        }
      })
    })
  },
  goto_Comm(e){
    app.globalData.ble_device = e.currentTarget.dataset
    this.stopBluetoothDevicesDiscovery()
    this.gotoconnect();
    // wx.navigateTo({
    //   // url: '/pages/comm/comm',
    //   url: "/pages/device/home/home", 
    // })
  },
  createBLEConnection(e) {
    const ds = e.currentTarget.dataset
    const deviceId = ds.deviceId
    const name = ds.name
    wx.createBLEConnection({
      deviceId,
      success: (res) => {
        this.setData({
          connected: true,
          name,
          deviceId,
        })
        this.getBLEDeviceServices(deviceId)
      }
    })
    this.stopBluetoothDevicesDiscovery()
  },
  closeBLEConnection() {
    wx.closeBLEConnection({
      deviceId: this.data.deviceId
    })
    this.setData({
      connected: false,
      chs: [],
      canWrite: false,
    })
  },
  getBLEDeviceServices(deviceId) {
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        for (let i = 0; i < res.services.length; i++) {
          if (res.services[i].isPrimary) {
            this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
            return
          }
        }
      }
    })
  },
  getBLEDeviceCharacteristics(deviceId, serviceId) {
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i]
          if (item.properties.read) {
            wx.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            })
          }
          if (item.properties.write) {
            this.setData({
              canWrite: true
            })
            this._deviceId = deviceId
            this._serviceId = serviceId
            this._characteristicId = item.uuid
            this.writeBLECharacteristicValue()
          }
          if (item.properties.notify || item.properties.indicate) {
            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
            })
          }
        }
      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      }
    })
    // 操作之前先监听，保证第一时间获取数据
    wx.onBLECharacteristicValueChange((characteristic) => {
      const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)
      const data = {}
      if (idx === -1) {
        data[`chs[${this.data.chs.length}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      } else {
        data[`chs[${idx}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      }
      // data[`chs[${this.data.chs.length}]`] = {
      //   uuid: characteristic.characteristicId,
      //   value: ab2hex(characteristic.value)
      // }
      this.setData(data)
    })
  },
  writeBLECharacteristicValue() {
    // 向蓝牙设备发送一个0x00的16进制数据
    let buffer = new ArrayBuffer(1)
    let dataView = new DataView(buffer)
    dataView.setUint8(0, Math.random() * 255 | 0)
    wx.writeBLECharacteristicValue({
      deviceId: this._deviceId,
      serviceId: this._deviceId,
      characteristicId: this._characteristicId,
      value: buffer,
    })
  },
  closeBluetoothAdapter() {
    wx.closeBluetoothAdapter()
    this._discoveryStarted = false
  },
  gotoabout: function () {
        console.log("current-Page-Length:",getCurrentPages().length)
        if(getCurrentPages().length > 8)
        {
          wx.reLaunch({
            url: '/pages/about/about',
          })
          
        }
        else{
          wx.navigateTo({
            url: '/pages/about/about',
          })
        }

  },
  gotosetuuid(){
        console.log("current-Page-Length:",getCurrentPages().length)
        if(getCurrentPages().length > 8)
        {
          wx.reLaunch({
            url: '/pages/setuuid/setuuid',
          })
          
        }
        else{
          wx.navigateTo({
            url: '/pages/setuuid/setuuid',
          })
        }
  },
  gotoconnect(){
    if(app.globalData.connected){
      wx.closeBLEConnection({
        deviceId: app.globalData.deviceId,
      })
      console.warn("DisConnect ", app.globalData.deviceId)
      app.globalData.connected = false
    } else {
      // 检查是否被别人绑定过
      var name = app.globalData.ble_device.name
      if(this.checkBlueIfBinded(name)){
          return
      }

      bluetooth.bluetoothInit((res)=>{
        if(res == true){
          console.info("获取特征值成功，跳转到home页面")
          //保存蓝牙设备信息
          app.globalData.bluetoothName = app.globalData.ble_device.name
          app.globalData.bluetoothMac = app.globalData.deviceId
          wx.request({
            url: 'https://cqygdqkj.top/api/v1/zqwb/blue_info/',
            method: "POST",
            header: {
              "Authorization": app.globalData.headerToken
            },
            data: {
                  "blue_name": app.globalData.bluetoothName,
                  "mac_code": app.globalData.bluetoothMac,
            },
            success(res){
              console.log(res)
            }
          })
              console.log("current-Page-Length:",getCurrentPages().length)
              if (getCurrentPages().length > 8)
              {
                wx.reLaunch({
                  url: '/pages/device/home/home',
                })
                
              }
              else{
                wx.navigateTo({
                  url: '/pages/device/home/home',
                })
              }

        }
      })
      setTimeout(() => {
        if(app.globalData.connected == false){
          console.warn("连接蓝牙超时失败")
        }
      }, 5000);
    }
  },
  onShow(){ //只要进到这个连接蓝牙的界面，就先断开蓝牙
    if(app.globalData.connected){
      wx.closeBLEConnection({
        deviceId: app.globalData.deviceId,
      })
      console.warn("DisConnect ", app.globalData.deviceId)
      app.globalData.connected = false
      wx.offBLEConnectionStateChange()
    }
  },
  test(){
    if(this.checkBlueIfBinded(app.data.testName)){
        return
    }
    
        console.log("current-Page-Length:",getCurrentPages().length)
        if (getCurrentPages().length > 8)
        {
          wx.reLaunch({
            url: '../device/home/home',
          })
          
        }
        else{
          wx.navigateTo({
            url: '../device/home/home',
          })
        }
  },
  checkBlueIfBinded(blueName) {
    var isBinded = false;
    var result = app.checkIsBindedByNameOfInfo(blueName)
    if(result == 1)
        isBinded = true
    console.log(blueName," isBinded=", isBinded)
    if(isBinded){
        wx.showToast({
          title: '设备已被绑定',
          icon: 'error'
        })
    }
    return isBinded;
  }
})
